package com.appleyk.security.springmvc.service.impl;

import com.appleyk.security.springmvc.model.AuthenticationUser;
import com.appleyk.security.springmvc.model.UserDto;
import com.appleyk.security.springmvc.service.AuthService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>越努力，越幸运</p>
 * 用户认证具体实现业务类
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  7:51 下午 2021/1/3
 */
@Service
public class AuthServiceImpl implements AuthService {

    private Map<String, UserDto> users = new HashMap<>();

    {
        // 手动赋予权限，要想对用户的权限的进行校验，需要配合拦截器来使用
        Set<String> _admin_purview = new HashSet<>();
        _admin_purview.add("p1");// 相当于admin具有访问资源r1的权限
        // 模拟数据库查询
        users.put("admin", new UserDto("admin", "admin123", "云清扬", "admin123@qq.com",_admin_purview));

        Set<String> _appleyk_purview = new HashSet<>();
        _appleyk_purview.add("p2");// 相当于appleyk具有访问资源r2的权限
        users.put("appleyk", new UserDto("appleyk", "123456a", "山治", "437704792@qq.com",_appleyk_purview));
    }

    /**
     * 模拟用户登录认证（实际上，security也是这个流程）
     * @param authUser 认证用户
     * @return 认证通过后的用户信息
     */
    @Override
    public UserDto login(AuthenticationUser authUser) {

        // 1、首先，判断userName和密码是否不为空
        if (authUser == null || authUser.getUserName() == null || "".equals(authUser.getUserName())) {
            throw new RuntimeException("用户名为空，认证失败！");
        }

        if (authUser.getPassword() == null || "".equals(authUser.getPassword())) {
            throw new RuntimeException("用户密码为空，认证失败！");
        }

        String userName = authUser.getUserName();
        String password = authUser.getPassword();

        // 2、其次，判断下用户是否在数据库中（当前模拟的是在内存中）存在
        if (!users.containsKey(userName)) {
            throw new RuntimeException("当前用户不存在！");
        }

        UserDto userDto = users.get(userName);

        // 3、如果用户名存在，就比对密码
        if (!userDto.getPassword().equals(password)) {
            throw new RuntimeException("当前用户密码不正确，认证失败！");
        }

        return userDto;
    }
}
